using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Roles;

namespace Team.API.Applocation.Handler.Users.Roles
{
    /// <summary>
    /// 查询角色处理器
    /// </summary>
    public class QueryRoleHandler : IRequestHandler<QueryRoleCommand, APIPaging<RoleDTO>>
    {
        private readonly IRepository<Rolemodel> roleRepository;

        public QueryRoleHandler(IRepository<Rolemodel> roleRepository)
        {
            this.roleRepository = roleRepository;
        }

        public async Task<APIPaging<RoleDTO>> Handle(QueryRoleCommand request, CancellationToken cancellationToken)
        {
            int pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
            int pageSize = request.PageSize <= 0 ? 10 : request.PageSize;

            var query = roleRepository.GetAll()
                .Where(r => r.IsDel == false)
                .WhereIF(!string.IsNullOrWhiteSpace(request.RoleName),
                    r => r.RoleName.Contains(request.RoleName!.Trim()))
                .WhereIF(request.Status.HasValue, r => r.Status == request.Status!.Value)
                .WhereIF(request.RoleType.HasValue, r => r.RoleType == request.RoleType!.Value)
                .OrderBy(r => r.Id, OrderByType.Desc)
                .Select(r => new RoleDTO
                {
                    Id = r.Id,
                    RoleCode = r.RoleCode,
                    RoleName = r.RoleName,
                    Description = r.Description,
                    Status = r.Status,
                    RoleType = r.RoleType,
                    Remark = r.Remark,
                    //CreateDate = r.Createdate,
                    //CreateName = r.Createname,
                    //UpdateDate = r.Updatedate,
                    //UpdateName = r.Updatename
                });

            int totalCount = 0;
            var result = query.ToPageList(pageIndex, pageSize, ref totalCount);

            return new APIPaging<RoleDTO>
            {
                Totalcount = totalCount,
                Code = StateCode.OK,
                Message = "获取角色列表成功",
                ListResult = result
            };
        }
    }
}
